const resolve = require('@rollup/plugin-node-resolve');
const commonjs = require('@rollup/plugin-commonjs');
const babel = require('@rollup/plugin-babel');
const terser = require('@rollup/plugin-terser');

const pkg = require('./package.json');

// 横幅注释
const banner = `/**
 * ${pkg.name} v${pkg.version}
 * ${pkg.description}
 * 
 * @author ${pkg.author}
 * @license ${pkg.license}
 * @homepage ${pkg.homepage}
 */`;

// 基础配置
const baseConfig = {
  input: 'src/index.js',
  plugins: [
    resolve({
      browser: true,
      preferBuiltins: false
    }),
    commonjs(),
    babel({
      babelHelpers: 'bundled',
      exclude: 'node_modules/**',
      presets: [
        ['@babel/preset-env', {
          modules: false,
          targets: {
            browsers: ['> 1%', 'last 2 versions', 'not dead']
          }
        }]
      ]
    })
  ],
  external: []
};

// 开发版本
const devConfig = {
  ...baseConfig,
  output: [
    {
      file: 'dist/sinma.js',
      format: 'umd',
      name: 'sinma',
      banner,
      sourcemap: true
    },
    {
      file: 'dist/sinma.esm.js',
      format: 'esm',
      banner,
      sourcemap: true
    },
    {
      file: 'dist/sinma.cjs.js',
      format: 'cjs',
      banner,
      sourcemap: true,
      exports: 'default'
    }
  ]
};

// 生产版本
const prodConfig = {
  ...baseConfig,
  plugins: [
    ...baseConfig.plugins,
    terser({
      format: {
        comments: function(node, comment) {
          // 保留许可证注释
          return comment.type === 'comment2' && /@license|@author|@version/.test(comment.value);
        }
      }
    })
  ],
  output: [
    {
      file: 'dist/sinma.min.js',
      format: 'umd',
      name: 'sinma',
      banner,
      sourcemap: true
    },
    {
      file: 'dist/sinma.esm.min.js',
      format: 'esm',
      banner,
      sourcemap: true
    }
  ]
};

// 兼容版本（支持IE9+）
const legacyConfig = {
  ...baseConfig,
  plugins: [
    resolve({
      browser: true,
      preferBuiltins: false
    }),
    commonjs(),
    babel({
      babelHelpers: 'bundled',
      exclude: 'node_modules/**',
      presets: [
        ['@babel/preset-env', {
          modules: false,
          targets: {
            ie: '9'
          },
          useBuiltIns: 'usage',
          corejs: 3
        }]
      ]
    }),
    terser({
      format: {
        comments: function(node, comment) {
          return comment.type === 'comment2' && /@license|@author|@version/.test(comment.value);
        }
      }
    })
  ],
  output: [
    {
      file: 'dist/sinma.legacy.min.js',
      format: 'umd',
      name: 'sinma',
      banner,
      sourcemap: true
    }
  ]
};

module.exports = [devConfig, prodConfig, legacyConfig];